import java.io.*;
import javax.sound.midi.*;

public class sortieMid {
	private static final int VELOCITY = 64;

	// ecriture du fichier midi
	protected static void write(String sortie) throws Exception {
		int compteur;
		File outputFile = new File(sortie);
		Sequence sequence = new Sequence(Sequence.PPQ, 1, 4);
		{ // Soprano
			Track track = sequence.createTrack();
			// vibraphone
			track.add(instrument(11, 1));
			for (int i = 0; i <= notes.midisoprano.length - 1; i++) {
				track.add(noteOn(notes.midisoprano[i], i, 1));
				track.add(noteOff(notes.midisoprano[i], i
						+ split.chainetemps[i], 1));
			}
		}

		{ // alto
			compteur = 0;
			Track track = sequence.createTrack();
			// Nylon Accustic Guitar instrument
			track.add(instrument(24, 2));
			for (int i = 0; i <= notes.midialto.length - 1; i++) {
				for (int j = 0; j < split.chainetemps[i]; j++) {
					track.add(noteOn(notes.midialto[i], i, 2));
					track.add(noteOff(notes.midialto[i], i + 1, 2));
				}
			}

		}

		{ // tenor
			compteur = 0;
			Track track = sequence.createTrack();
			// Shakuhachi instrument
			track.add(instrument(77, 3));
			for (int i = 0; i <= notes.miditenor.length - 1; i++) {
				for (int j = 0; j < split.chainetemps[i]; j++) {
					track.add(noteOn(notes.miditenor[i], i, 3));
					track.add(noteOff(notes.miditenor[i], i + 1, 3));
				}
			}

		}

		{ // basse
			compteur = 0;
			Track track = sequence.createTrack();
			// Kalimba instrument
			track.add(instrument(108, 4));
			for (int i = 0; i <= notes.midibasse.length - 1; i++) {
				for (int j = 0; j < split.chainetemps[i]; j++) {
					track.add(noteOn(notes.midibasse[i], i, 4));
					track.add(noteOff(notes.midibasse[i], i++, 4));
				}
			}
		}

		MidiSystem.write(sequence, 1, outputFile);
		System.out.println("fichier " + sortie + " écrit");
	}

	private static MidiEvent noteOn(int nKey, long lTick, int canal)
			throws InvalidMidiDataException {
		return createNoteEvent(ShortMessage.NOTE_ON, nKey, VELOCITY, lTick,
				canal);
	}

	private static MidiEvent noteOff(int nKey, long lTick, int canal)
			throws InvalidMidiDataException {
		return createNoteEvent(ShortMessage.NOTE_OFF, nKey, 0, lTick, canal);
	}

	private static MidiEvent instrument(int instrument, int canal)
			throws InvalidMidiDataException {
		return createNoteEvent(ShortMessage.PROGRAM_CHANGE, instrument, 0, 0,
				canal);
	}

	private static MidiEvent createNoteEvent(int nCommand, int nKey,
			int nVelocity, long lTick, int canal)
			throws InvalidMidiDataException {
		ShortMessage message = new ShortMessage();
		message.setMessage(nCommand, canal, nKey, nVelocity);
		return new MidiEvent(message, lTick);
	}
}